package database

import (
	"{{.projectName}}/model"
	"{{.projectName}}/service"
	"{{.projectName}}/variable"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"github.com/apache/rocketmq-client-go/v2"
    "github.com/apache/rocketmq-client-go/v2/consumer"
    "github.com/apache/rocketmq-client-go/v2/producer"
    cron "github.com/robfig/cron/v3"
)

var (
	err error
)

func init() {
	dsn := "root:new_password@tcp(127.0.0.1:3306)/{{Snake .projectName}}?charset=utf8mb4&parseTime=True&loc=Local"
	variable.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("db error")
	}

	sqlDb, pErr := variable.DB.DB()
	if pErr != nil {
		panic("db error")
	}
	sqlDb.SetMaxIdleConns(10)
	sqlDb.SetMaxOpenConns(100)
	sqlDb.SetConnMaxLifetime(time.Hour)

	variable.DB.AutoMigrate(&model.{{.structName}}{})

	pool := &redis.Pool{
    		MaxIdle:     10,
    		MaxActive:   0,
    		IdleTimeout: 100,
    		Dial: func() (redis.Conn, error) {
    			return redis.Dial("tcp", "127.0.0.1:6379")
    		},
    	}
    variable.REDIS = pool.Get()

    variable.PRODUCE, err = rocketmq.NewProducer(
        producer.WithNameServer([]string{"127.0.0.1:9876"}), // 接入点地址
        producer.WithRetry(3),                  // 重试次数
        producer.WithGroupName("ProductGroup"), // 分组名称
    )
    if err != nil {
        fmt.Println("rocketmq producer init err：", err)
    }

    variable.CONSUMER, err = rocketmq.NewPushConsumer(
        consumer.WithNameServer([]string{":127.0.0.1:9876"}), // 接入点地址
        consumer.WithConsumerModel(consumer.Clustering),
        consumer.WithGroupName("ConsumerGroup"), // 分组名称
    )
    if err != nil {
        fmt.Println("rocketmq consumer init err：", err)
    }

    scheduled := cron.New()

    // 添加定时任务, * * * * * 是 crontab,表示每分钟执行一次
    _, err = scheduled.AddFunc("* * * * *", service.New{{.structName}}Service().{{.structName}}Task())
    if err != nil {
        fmt.Println("{{Lower .structName}} cron init err：", err)
    }

    // 启动定时器
    scheduled.Start()
}

